package cn.softgame.jserver.connector;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import cn.softgame.jserver.queue.MessageQueue;
import cn.softgame.jserver.queue.QueueFactory;

/**
 * 本类是供Socket I/O调用，以实现信号的发送和收取
 * 是MessageQueue与Socket I/O的接口部分
 * @author lenovo
 *
 */
public class SocketDataHandler {
	private final static WrapFactory wrapFactory = WrapFactory.getInstance();
	private final static QueueFactory queueFactory = QueueFactory.getInstance();
	private final static MessageQueue messageQueue = MessageQueue.getInstance();
	private final static int DATA_LENGTH=1024;
	private int queueType;
	
	public SocketDataHandler(){}
	
	public SocketDataHandler(int queueType){
		this.queueType=queueType;
	}
	
	//获得特定大小的byte数组，以接受数据，可根据应用调整
	public byte[] getByte(){
		return new byte[DATA_LENGTH];
	}
	
	/**
	 * 从Queue中取出Request 并实行协议包装
	 * @return
	 */
	public byte[] sendRequest(){
		byte[] request=null;
		try {
			ByteArrayOutputStream outByte = (ByteArrayOutputStream) messageQueue.removeReqFirst();
			request = wrapFactory.getRequest(outByte.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return request;
	}
	
	/**
	 * 从Queue中取出Response 并实行协议包装
	 * @return
	 */
	public byte[] sendResponse(){
		byte[] response=null;
		try {
			ByteArrayOutputStream outByte = (ByteArrayOutputStream) messageQueue.removeReqFirst();
			response = wrapFactory.getResponse(outByte.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}
	
	public void receiveResponse(byte[] array) throws Exception{
		MessageQueue messageQueue = queueFactory.getQueue(queueType);
		byte[] response = wrapFactory.getContentFromResponse(array);
		InputStream in = new ByteArrayInputStream(response);
		messageQueue.pushResponse(in);
	}
}
